import datetime
from .db import cursor, conn
from utils.print_message import print_message

def select_weibo_by_weibo_id(weibo_id):
    sql = """
    SELECT * FROM weibo_info WHERE weibo_id = %s
    """
    cursor.execute(sql, (weibo_id,))
    return cursor.fetchone()

def insert_weibo(weibo_class):
    data = weibo_class.json()
    now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    data['create_time'] = now
    data['update_time'] = now

    columns = ", ".join(data.keys())
    placeholders = ", ".join(["%s"] * len(data))
    sql = f"INSERT INTO weibo_info ({columns}) VALUES ({placeholders})"
    params = tuple(data.values())

    cursor.execute(sql, params)
    conn.commit()
    return cursor.rowcount


def update_weibo(weibo_class):
    data = weibo_class.json()

    # 假设用 user_id 作为更新条件，不会更新它本身
    weibo_id = data.pop('weibo_id')

    # 拼接字段=占位符，如 "name=%s, followers_count=%s, ..."
    set_clause = ", ".join([f'{k}=%s' for k in data.keys()])
    
    sql = f"UPDATE weibo_info SET {set_clause} WHERE weibo_id = %s"
    # 用元组params
    params = tuple(data.values()) + (weibo_id,)
    
    cursor.execute(sql, params)
    conn.commit()
    return cursor.rowcount

def count_activity_by_release_time(user_id, start_time, end_time):
    # 统计赞、评论、转发数量
    sql = """
    SELECT SUM(attitudes) AS likes, SUM(comments) AS comments, SUM(reposts) AS reposts FROM weibo_info WHERE user_id = %s AND release_time BETWEEN %s AND %s
    """
    params = (user_id, start_time, end_time)
    # complete_sql = cursor.mogrify(sql, params)  
    # print("完整SQL:", complete_sql)
    
    cursor.execute(sql, params)
    return cursor.fetchone()

# 根据user_id获取最近更新update_time的一条微博
def select_weibo_by_update_time(user_id, limit = 1):
    sql = """
    SELECT * FROM weibo_info WHERE user_id = %s ORDER BY update_time DESC LIMIT %s
    """
    params = (user_id, limit)
    # complete_sql = cursor.mogrify(sql, params)  
    # print("完整SQL:", complete_sql)
    cursor.execute(sql, params)
    return cursor.fetchall()

# 获取比输入日期更晚的微博
def select_weibo_by_date(user_id, date):
    sql = """
    SELECT * FROM weibo_info WHERE user_id = %s AND update_time > %s
    """
    cursor.execute(sql, (user_id, date))
    return cursor.fetchall()